import DICOMWeb from '../DICOMWeb';

export default ({ method, url, headers }) => {
  return new Promise((resolve, reject) => {
    const oReq = new XMLHttpRequest();

    oReq.addEventListener('error', error => {
      reject(new Error('An error occurred while retrieving the JSON data'));
    });
    oReq.addEventListener('load', event => {
      if (event.target.status === 404) {
        reject(new Error('No JSON data found'));
        return;
      }

      if (!oReq.responseText) {
        reject(new Error('Response was undefined'));
        return;
      }

      try {
        resolve(JSON.parse(oReq.responseText));
      } catch (err) {
        reject(new Error('Json data parse failed.'));
      }
    });

    oReq.open(method, url);
    const oathHeaders = DICOMWeb.getAuthorizationHeader();
    const mergedHeaders = { ...headers, ...oathHeaders };
    Object.keys(mergedHeaders).forEach(k => {
      oReq.setRequestHeader(k, mergedHeaders[k]);
    });
    oReq.send();
  });
}
